package com.wwwarehouse.usercenter.fragment.invite;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.adapter.carddesk.MyFragmentPagerAdapter;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.SlideBarView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.eventbus_event.DrawerSingleSelectEvent;
import com.wwwarehouse.common.fragment.DeskDrawerSingleFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.bean.response.InviteInfoResponseBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;

/**
 * Created by Jackie on 2017/8/15.
 * 查看已邀请的人
 */
public class ShowInvitedFragment extends BaseFragment {
    private View mRootView;
    private LinearLayout mResultLayout;
    private LinearLayout mEmptyLayout;
    private ImageView mEmptyImg;
    private TextView mEmptyTxt;

    private StateLayout mStateLayout;
    protected ElasticScrollView mElasticScrollView;
    private CustomViewPagerInternal mCustomViewPagerInternal;
    private CirclePageIndicator mCirclePageIndicator;
    private SlideBarView mSlideBarView;
    private List<Fragment> mFragmentList;

    protected String mMobile;
    protected String mName;
    protected Set<Integer> mStatusSet;
    protected String mSort;

    protected int mSelectedBubblePosition = 1;

    protected InviteDetailsFragment mInviteDetailsFragment;
    protected Bundle mBundle;

    private static final int REQUEST_GET_INVITE_INFO = 0;

    public static final int PAGE = 1;
    public static final int SIZE = 9;

    public static final String KEY_INVITE_MOBILE = "key_invite_mobile";
    public static final String KEY_INVITE_NAME = "key_invite_name";
    public static final String KEY_INVITE_STATUS = "key_invite_status";
    public static final String KEY_INVITE_SORT = "key_invite_sort";
    public static final String KEY_INVITE_PAGE = "key_invite_page";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_show_invited, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        mResultLayout = findView(mRootView, R.id.ll_result);
        mEmptyLayout = findView(mRootView, R.id.ll_empty);
        mEmptyImg = findView(mRootView, R.id.iv_empty);
        mEmptyTxt = findView(mRootView, R.id.tv_empty);

        mStateLayout = findView(mRootView, R.id.sl_layout);

        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mStateLayout.getProgressviewLayoutparam();
        params.bottomMargin += ConvertUtils.dip2px(mActivity, 19);
        mStateLayout.showProgressView(false);

        mElasticScrollView = findView(mRootView, R.id.esv_elastic);
        mCustomViewPagerInternal = findView(mRootView, R.id.vpi_invite);
        mCirclePageIndicator = findView(mRootView, R.id.cpi_indicator);
        mSlideBarView = findView(mRootView, R.id.sbv_slide);

        mFragmentList = new ArrayList<>();

        //设置抽屉数据
        List<FilterBean> filterList = new ArrayList<>();
        for (String value : getResources().getStringArray(R.array.invite_filter_value)) {
            filterList.add(new FilterBean(false, value));
        }

        //默认第一个选中
        filterList.get(0).setSelect(true);

        //多选
//        DeskDrawerMultipleFragment deskDrawerMultipleFragment = DeskDrawerMultipleFragment.newInstance(getString(R.string.register_state), filterList, 3);
        //单选
        DeskDrawerSingleFragment deskDrawerSingleFragment = DeskDrawerSingleFragment.newInstance(getString(R.string.register_state), filterList);
        ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerSingleFragment);

        mMobile = "";
        mName = "";
        mStatusSet = generateStatusSet();
        mSort = "INVITEE_STATUS";

        EventBus.getDefault().register(this);
    }

    public void onEventMainThread(DrawerSingleSelectEvent event) {
        mStatusSet.clear();

        int[] keys = getResources().getIntArray(R.array.invite_filter_key);
        if (event.getSelectedPosition() == 0) {
            //全部
        } else {
            mStatusSet.add(keys[event.getSelectedPosition()]);
        }

        getInviteInfo("", "", mStatusSet, mSort);
    }

    private void initEvent() {
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                ((BaseCardDeskActivity) mActivity).downPull_4();
            }

            @Override
            public void onUpPull() {

            }
        });
    }

    @Override
    public void filterClick() {
        if (peekFragment() instanceof ShowInvitedFragment) {
            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() instanceof ShowInvitedFragment) {
            if (!TextUtils.isEmpty(text)) {
                if (text.matches("^[0-9]*$")) {
                    mMobile = text;
                } else {
                    mName = text;
                }

                getInviteInfo(mMobile, mName, mStatusSet, mSort);
            }
        }
    }

    @Override
    public void cancelClick() {
        mMobile = "";
        mName = "";

        getInviteInfo(mMobile, mName, mStatusSet, mSort);
    }

    @Override
    public void sortClick(View anchor) {
        if (peekFragment() instanceof ShowInvitedFragment) {
            PopUpUtils.showBubbleInviteSort(mActivity, anchor, mSelectedBubblePosition, new PopUpUtils.OnChoiceListener() {
                @Override
                public void onChoice(int position) {
                    mSelectedBubblePosition = position;

                    switch (position) {
                        case 1:
                            mSort = "INVITEE_STATUS";      //默认排序，邀请状态排序
                            break;
                        case 2:
                            mSort = "INVALID_TIME";        //邀请时间正序
                            break;
                        case 3:
                            mSort = "INVALID_TIME DESC ";  //邀请时间倒序
                            break;
                        default:
                            break;
                    }

                    getInviteInfo(mMobile, mName, mStatusSet, mSort);
                }
            });
        }
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ShowInvitedFragment) {
            mActivity.setTitle(R.string.view_invited);
        }
    }

    @Override
    public void requestDatas() {
        getInviteInfo("", "", mStatusSet, mSort);
    }

    protected void getInviteInfo(String mobile, String name, Set<Integer> statusSet, String sort) {
        Map map = new HashMap();

        if (!TextUtils.isEmpty(mobile)) {
            map.put("inviteeMobile", mobile);
        }

        if (!TextUtils.isEmpty(name)) {
            map.put("inviteeName", name);
        }

        if (statusSet != null && statusSet.size() > 0) {
            map.put("inviteeList", statusSet);
        }

        map.put("page", PAGE);
        map.put("size", SIZE);
        map.put("sort", sort);

        NoHttpUtils.httpPost(UserCenterConstant.URL_GET_INVITE_INFO, map, mOnResponseListener, REQUEST_GET_INVITE_INFO);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_GET_INVITE_INFO:
                    if ("0".equals(commonClass.getCode())) {
                        InviteInfoResponseBean inviteInfoResponseBean = JSON.parseObject(commonClass.getData().toString(), InviteInfoResponseBean.class);

                        //总共多少页
                        int total = inviteInfoResponseBean.getTotal();
                        if (total == 0) {
                            if (TextUtils.isEmpty(mMobile) && TextUtils.isEmpty(mName)) {
                                //没有请求数据
                                mResultLayout.setVisibility(View.VISIBLE);
                                mEmptyLayout.setVisibility(View.GONE);

                                mStateLayout.showEmptyView(false);
                                mStateLayout.setEmptyListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        mStateLayout.showProgressView(false);

                                        getInviteInfo("", "", mStatusSet, mSort);
                                    }
                                });
                            } else {
                                //没有搜索结果
                                mResultLayout.setVisibility(View.GONE);
                                mEmptyLayout.setVisibility(View.VISIBLE);

                                mEmptyImg.setImageResource(R.drawable.search_empty);
                                mEmptyTxt.setText(R.string.invite_search_no_result);
                            }
                        } else {
                            mResultLayout.setVisibility(View.VISIBLE);
                            mEmptyLayout.setVisibility(View.GONE);

                            int page = (total % 9 == 0) ? total / 9 : (total / 9 + 1);

                            mFragmentList.clear();

                            for (int i = 0; i < page; i++) {
                                mBundle = new Bundle();
                                newFragment(i);
                                mInviteDetailsFragment.setArguments(mBundle);
                                mFragmentList.add(mInviteDetailsFragment);
                            }

                            mCustomViewPagerInternal.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), mFragmentList));

                            if (page <= 6) {
                                if (page > 1) {
                                    mCirclePageIndicator.setVisibility(View.VISIBLE);
                                    mSlideBarView.setVisibility(View.GONE);

                                    mCirclePageIndicator.setViewPager(mCustomViewPagerInternal, 0);
                                } else {
                                    mCirclePageIndicator.setVisibility(View.GONE);
                                    mSlideBarView.setVisibility(View.GONE);
                                }
                            } else {
                                mCirclePageIndicator.setVisibility(View.GONE);
                                mSlideBarView.setVisibility(View.VISIBLE);

                                mSlideBarView.setTotalPage(page);
                                mSlideBarView.setOnSlideChange(new SlideBarView.OnSlideChange() {
                                    @Override
                                    public void onSlideChange(int page) {
                                        mCustomViewPagerInternal.setCurrentItem(page, false);
                                    }
                                });

                                mSlideBarView.setViewPagerInternal(mCustomViewPagerInternal);
                            }
                        }
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), false);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mStateLayout.showProgressView(false);

                                getInviteInfo("", "", mStatusSet, mSort);
                            }
                        });
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            mStateLayout.showNetworkView(false);
            mStateLayout.setNetworkListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mStateLayout.showProgressView(false);

                    getInviteInfo("", "", mStatusSet, mSort);
                }
            });
        }

        @Override
        public void onFinish(int what) {
            mStateLayout.showContentView();
        }
    };

    // 修改搜索条件
    protected Set<Integer> generateStatusSet() {
        mStatusSet = new HashSet<>();

        return mStatusSet;
    }

    protected void newFragment(int i) {
        newFragment();

        if (!TextUtils.isEmpty(mMobile)) {
            mBundle.putString(KEY_INVITE_MOBILE, mMobile);
        }

        if (!TextUtils.isEmpty(mName)) {
            mBundle.putString(KEY_INVITE_NAME, mName);
        }

        if (mStatusSet != null && mStatusSet.size() > 0) {
            mBundle.putSerializable(KEY_INVITE_STATUS, (Serializable) mStatusSet);
        }

        mBundle.putString(KEY_INVITE_SORT, mSort);
        mBundle.putInt(KEY_INVITE_PAGE, (i + 1));
    }

    protected void newFragment() {
        mInviteDetailsFragment = new InviteDetailsFragment();
    }
}
